<template>
  <div class="injureReport">
    <div class="injureReport-header">
      <el-card class="drug-head-contatiner-title2" shadow="never">
        <!-- <h2>杭州亚(残) 运会传染病症状监测日报汇总表</h2> -->
        <h2>亚冬会传染病症状监测日报汇总表</h2>
        <el-form
          :inline="true"
          :model="formSearch"
          ref="searchDialogRef"
          class="demo-form-inline"
          :rules="reportAsiaInfactFormRulesMixin.searchFormRules"
        >
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formSearch.startTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formSearch.endTime"
              type="datetime"
              placeholder="--请选择--"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="所属城市" prop="citycode">
            <el-tree-select
              v-model="formSearch.citycode"
              :data="cityTreeOption"
              :props="defaultProps"
              node-key="Code"
              :check-strictly="true"
              :render-after-expand="false"
              clearable
              filterable
            />
          </el-form-item>
          <el-form-item label="场馆">
            <el-select
              v-model="formSearch.activityvenuescode"
              placeholder="--选择--"
              ref="venuesRef"
              filterable
              clearable
            >
              <el-option
                v-for="item in activityVenuesOption"
                :key="item.Code"
                :label="item.CHIDescription"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="是否测试" prop="isTest">
            <el-select
              v-model="formSearch.isTest"
              placeholder="--选择--"
              clearable
              filterable
            >
              <el-option key="1" label="是" value="1" />
              <el-option key="0" label="否" value="0" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <!-- <el-button
              v-model="formSearch.ifDevide"
              type="primary"
              @click="formSearch.ifDevide = !formSearch.ifDevide"
              >{{ formSearch.ifDevide ? '分页预览' : '整体预览' }}</el-button
            > -->
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button type="primary" @click="onlyPrint">打印</el-button>
            <el-dropdown @command="handleCommand" style="margin: 10px">
              <el-button type="primary">
                导出<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="a">Excel</el-dropdown-item>
                  <el-dropdown-item command="b">pdf</el-dropdown-item>
                  <el-dropdown-item command="c">Word</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="injureReport-list" v-loading="loading">
      <iframe
        src=""
        frameborder="0"
        id="print-iframe"
        width="100%"
        height="700px"
        title="预览窗格"
      ></iframe>
    </div>
    <div>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { reportAsiaInfactFormRulesMixin } from '@/utils/mixin';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Base64 } from 'js-base64';
import store from '@/store';
import { getAsiaInfectStatistics } from '@/network/report';
import { getActivityVenues, getCityTree } from '@/network/dictionary.js';
const venuesRef = ref(null);
const cityTreeOption = ref([]);
const activityVenuesOption = ref([]);
const searchDialogRef = ref(null);
const loading = ref(true);
const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
const handleCommand = (command) => {
  switch (command) {
    case 'a':
      // exportFile('杭州亚(残)运会传染病症状监测日报汇总表.xlsx');
      exportFile('亚冬会传染病症状监测日报汇总表.xlsx');

      break;
    case 'b':
      // exportFile('杭州亚(残)运会传染病症状监测日报汇总表.pdf');
      exportFile('亚冬会传染病症状监测日报汇总表.pdf');

      break;
    case 'c':
      // exportFile('杭州亚(残)运会传染病症状监测日报汇总表.docx');
      exportFile('亚冬会传染病症状监测日报汇总表.docx');

      break;
    default:
      break;
  }
};
const exportFile = async (filename) => {
  let paramsPrint = {
    pageSize: formSearch.pageSize,
    page: formSearch.page,
    startTime: formSearch.startTime,
    endTime: formSearch.endTime,
    activityvenuescode: formSearch.activityvenuescode,
    citycode: formSearch.citycode,
    role: formSearch.Role,
    filename: filename,
    ifDevide: false,
    telephone: formSearch.Telephone,
    fillPerson: formSearch.Fillperson,
    isTest: formSearch.isTest,
  };
  await getAsiaInfectStatistics(paramsPrint, 'blob').then((ret) => {
    // debugger;
    let bytearray = Base64.toUint8Array(ret.data.FileContents);
    let blob = new Blob([bytearray]);
    const link = document.createElement('a'); //利用a标签自定义下载文件名
    link.style.display = 'none';
    //设置连接
    link.href = URL.createObjectURL(blob);
    link.download = filename; //自定义文件名字
    document.body.appendChild(link);
    // 模拟点击事件;
    link.click();
    link.parentNode.removeChild(link);
    URL.revokeObjectURL(link.href);
  });
};
const onSubmit = async () => {
  loading.value = true;
  initData();
};
//分页
const handleCurrentChange = (val) => {
  formSearch.page = val;
  initData();
};
//初始化数据
const initData = async () => {
  searchDialogRef.value.validate(async (valid) => {
    if (valid) {
      let data = {
        pageSize: formSearch.pageSize,
        page: formSearch.page,
        startTime: formSearch.startTime,
        endTime: formSearch.endTime,
        activityvenuescode: formSearch.activityvenuescode,
        citycode: formSearch.citycode,
        role: formSearch.Role,
        filename: 'cs.html',
        ifDevide: formSearch.ifDevide,
        telephone: formSearch.Telephone,
        fillPerson: formSearch.Fillperson,
        isTest: formSearch.isTest,
      };
      await getAsiaInfectStatistics(data).then((res) => {
        loading.value = false;
        let bytearray = Base64.decode(res.data.FileContents);
        formSearch.total = parseInt(res.total);
        //判断iframe是否存在，不存在则创建iframe
        var iframe = document.getElementById('print-iframe');
        var doc = null;
        doc = iframe.contentWindow.document;
        doc.write('<div>' + bytearray + '</div>');
        doc.close();
        iframe.contentWindow.focus();
      });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
// 定义全局变量
let venuesOptionArray = [];
const init = async () => {
  await getCityTree().then((res) => {
    cityTreeOption.value = res;
  });
  await getActivityVenues().then((res) => {
    activityVenuesOption.value = res;
    venuesOptionArray = res;
    // table.value.doLayout();
  });
  //监听watch
  watch(
    [() => formSearch.citycode, () => formSearch.activityvenuescode],
    (newValue, oldValue) => {
      // 城市变更--场馆变更--车辆变更--理疗店变更
      if (newValue[0] && newValue[0] != oldValue[0]) {
        formSearch.activityvenuescode = '';
        formSearch.ambulanceCode = '';
        formSearch.medicalPoint = '';
        //车辆都重新赋值
        activityVenuesOption.value = venuesOptionArray.filter(
          (it) => it.CityCode == newValue[0],
        );
      } else {
        activityVenuesOption.value = venuesOptionArray;
      }
    },
    {
      deep: true,
    },
  );
  //初始化受伤统计1
  initData();
};

onMounted(init);
const formSearch = reactive({
  startTime: getInitTime(),
  endTime: getInitTime(0, ' 23:59:59'),
  activityvenuescode: '',
  citycode: '',
  total: 0,
  page: 1,
  pageSize: 10,
  Role: null,
  ifDevide: true,
  Telephone: JSON.parse(store.state.app.userInfo).Telephone,
  Fillperson: JSON.parse(store.state.app.userInfo).Name,
  isTest: 0,
});
function getInitTime(intday, hour) {
  let secodenpast = new Date().getTime() - (intday || 0) * 24 * 60 * 60 * 1000;
  var now = new Date(secodenpast);
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth(); //得到月份
  var date = now.getDate(); //得到日期
  hour = hour || ' 00:00:00'; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
  month = month + 1;
  month = month.toString().padStart(2, '0');
  date = date.toString().padStart(2, '0');
  let x = `${year}-${month}-${date}${hour}`;
  return x;
}
const onReset = () => {
  formSearch.startTime = getInitTime();
  formSearch.endTime = getInitTime(0, ' 23:59:59');
  formSearch.activityvenuescode = '';
  formSearch.citycode = '';
};
const onlyPrint = () => {
  // window.print();
  var iframe = document.getElementById('print-iframe');
  iframe.contentWindow.print();
};
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  if (!data) {
    return sums;
  }
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      sums[index] += ' 个';
    } else {
      sums[index] = 'N/A';
    }
  });

  return sums;
};
</script>
<style lang="scss" scoped>
.injureReport {
  margin: 14px 15px 14px;
  .injureReport-header {
    .drug-head-contatiner-title2 {
      h2 {
        text-align: center;
        margin-bottom: 14px;
      }
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .injureReport-list {
    margin-top: 14px;
    // width: 500px;
  }
}
// /*字体调黑*/
:deep(.el-table) {
  font-size: 16px;
  color: #000000;
  border: 1px solid #dcdfe6;
}

:deep(.el-table th) {
  font-weight: normal;
  font-size: 18px;
}

:deep(.el-table thead) {
  color: #000000;
}

// /*边框调黑*/
:deep(.el-table::before) {
  background-color: #000000;
}

:deep(.el-table--border::after) {
  background-color: #000000;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border: 1px solid #000000;
}

:deep(.el-table--group),
:deep(.el-table--border) {
  border-color: #000000;
}

:deep(.el-table th.is-leaf),
:deep(.el-table td) {
  border-bottom: 1px solid #000000;
}

// /*减小单元格间距*/
:deep(.el-table th),
:deep(.el-table td) {
  padding: 0 0;
}

// /*显示底部边框 估计打印时伪元素把border覆盖了 height设为0隐藏伪元素*/
:deep(.el-table::before) {
  height: 0;
}

// /*显示右边框*/
:deep(.el-table--group::after),
:deep(.el-table--border::after) {
  width: 1;
}
</style>
